package com.sjq.common.util;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.sjq.common.entity.LoginAccount;
import com.sjq.common.entity.OperationLog;
import com.sjq.common.entity.Result;
import com.sjq.common.service.OperationLogService;
import com.sjq.common.web.SessionUserHelper;



public class SaveCzrzInterceptor extends HandlerInterceptorAdapter {
	@Resource
	private OperationLogService czrzService;
	
	private Logger logger=Logger.getLogger(SaveCzrzInterceptor.class);
	/**
	 * 获取ip
	 * @param req
	 * @return
	 */
	private String getIpAddress(HttpServletRequest req){
		String ip=req.getHeader("x-forwarded-for");
		if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
			ip=req.getHeader("Proxy-Client-IP");
		}
		if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
			ip=req.getHeader("WL-Proxy-Client-IP");
		}
		if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
			ip=req.getHeader("HTTP-CLIENT-IP");
		}
		if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
			ip=req.getHeader("HTTP-X-FORWARDED_FOR");
		}
		if(ip==null||ip.length()==0||"unknown".equalsIgnoreCase(ip)){
			ip=req.getRemoteAddr();
		}
		return ip;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler)
	throws Exception{
		try {
			  LoginAccount obj=SessionUserHelper.create(request).getLoginAccount();
		    
		
			  OperationLog czrz=new OperationLog();
		      czrz.setCazr_dwdm(obj.getUserDwbm());
		      czrz.setCazr_dwmc(obj.getUserDwmc());
		      czrz.setCazr_gmsfhm(obj.getUserId());
		      czrz.setCazr_xm(obj.getUserName());
		      czrz.setCazr_ipdz(getIpAddress(request));
		      Map<String, String[]> parameterMap= request.getParameterMap();
		      czrz.setCzcs(JSONObject.fromObject(parameterMap).toString());
		      czrz.setCzurl(request.getServletPath());
			//  System.out.println("-----1"+request.getServletPath());
			 // System.out.println("-----2"+JSONObject.fromObject(parameterMap).toString());
		   /*   Result<OperationLog>  result=czrzService.save(czrz);
		    
		      if(result.getStatus()!=0){
		    	  throw new Exception(result.getMsg());
		      }
		     */ 
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
      
		
		return super.preHandle(request, response, handler);
	}
	
    
}
